#include "stm32f10x.h"

#include "iwdg.h"
#include "led.h"
#include "soil_moisture.h"
#include "usart1.h"
#include "delay.h"

#include "kalman_filter.h"

static void SendHex(uint8_t bin)
{
    while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET)
    {
    }
    USART_SendData(USART1, bin);
}

int main()
{
    uint32_t tick_start = 0;
    KFS kfs = {
        .prevData = 0,
        .p = 1,
        .q = 0.001,
        .r = 0.1,
        .kGain = 0,
    };

    IWDG_Init();
    LED_Init();
    SOIL_MOISTURE_Init();
    USART1_Init();
    Delay_Init();

    while (1)
    {
        if (SOIL_MOISTURE_IsOk())
        {
            uint16_t adc_value = (uint16_t)KalmanFilter(&kfs, SOIL_MOISTURE_GetValue());
            if (Get_Tick() - tick_start > 500000)
            {
                tick_start = Get_Tick();
                IWDG_ReloadCounter();
                // Flicker LED
                GPIOB->ODR ^= GPIO_Pin_5;
                // 向串口发送 ADC Value 的值
                uint8_t high = adc_value >> 8;
                uint8_t low = adc_value;
                SendHex(high);
                SendHex(low);
                SendHex(~(high + low));
            }
        }
    }
}
